<template>
  <div :class="ns.b()">
    <div :class="ns.e('header')"></div>
    <div :class="ns.e('body')" ref="canvas"></div>
    <div :class="ns.e('footer')"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useNamespace } from '@mdfe/medi-ui';
import { init } from 'echarts';
import bIZuJianWH from '@/api/juecefxpt/bIZuJianWH';
import { transModelToPieData } from '@/views/zuJianSJ/components/widgetType/pie';
import elementResizeDetectorMaker from 'element-resize-detector';

defineOptions({
  name: 'mic-pie-block',
});

const props = defineProps({
  widgetStyle: Object,
  isComp: {
    type: Boolean,
    default: false,
  },
  widget: Object,
});

const ns = useNamespace('bi-pie-block');

const emit = defineEmits(['set', 'EchartClick']);

let instance = null;
const canvas = ref();

const style = ref();
const seriesOption = ref();

const erd = elementResizeDetectorMaker();

let resizeListener = null;

async function search(id, data) {
  const { xuanZhongWDList, xuanZhongZBList } = data;
  if (xuanZhongZBList.length == 0 && xuanZhongWDList.length == 0) return;
  data.zuJianTBLX = 2;

  // try {
  const res = await bIZuJianWH.generateDataList({
    gongChengSJJID: id,
    zuJianNR: JSON.stringify(data),
  });
  const zhiBiaoIndex = res.fieldList.findIndex((item) => {
    return item.ziDuanMC === data.xuanZhongZBList?.[0]?.ziDuanMC;
  });
  const obj = {
    dataset: {
      source: [],
    },
    series: [],
    legend: {
      data: [],
    },
  };
  obj.dataset.source.push(
    res.fieldList.map((item) => {
      return item.ziDuanMC;
    }),
  );
  res.fieldList.map((item, index) => {
    res.fieldList.forEach((e, i) => {
      if (index < zhiBiaoIndex && i >= zhiBiaoIndex) {
        const series = Object.assign({}, seriesOption.value, {
          type: 'pie',
          name: item.ziDuanMC + '/' + e.ziDuanMC,
          encode: {
            name: item.ziDuanMC,
            value: e.ziDuanMC,
          },
          center: [
            `${(100 * index + 50) / zhiBiaoIndex}%`,
            `${(100 * (i - zhiBiaoIndex) + 50) / (res.fieldList.length - zhiBiaoIndex)}%`,
          ],
          radius: [`${50 / zhiBiaoIndex}%`, 0],
        });
        obj.series.push(series);
        obj.legend.data.push(item.ziDuanMC + '/' + e.ziDuanMC);
      }
    });
  });
  if (res.data) {
    res.data.forEach((item) => {
      obj.dataset.source.push(item);
    });
  } else {
    obj.dataset.source = [];
  }

  instance.setOption(obj);
  // } catch (e) {
  //   console.error(e);
  // }
}
function setOption(options) {
  if (!options) return;
  style.value = options;
  const { series } = instance.getOption();
  const obj = transModelToPieData(options);
  seriesOption.value = Object.assign({}, seriesOption.value, obj.series);
  const newSeries = series.map((item) => {
    return Object.assign({}, item, seriesOption.value);
  });
  obj.series = newSeries;
  instance.setOption(obj);
}

onMounted(() => {
  nextTick(() => {
    instance = init(canvas.value);

    // 指定图表的配置项和数据

    style.value = props.widgetStyle || {};
    seriesOption.value = {};
    instance.setOption({
      series: [
        {
          type: 'pie',
        },
      ],
    });

    emit('set', true);

    instance.on('click', (params) => {
      emit('EchartClick', { echart: params, widget: props.widget });
    });

    if (props.isComp && props.widget) {
      search(props.widget.gongChengSJJID, props.widget);
      setOption(props.widget.styleConfig);

      resizeListener = erd.listenTo(canvas.value, () => {
        instance.resize();
      });
    }
  });
});

onBeforeUnmount(() => {
  if (resizeListener) {
    erd.uninstall(canvas.value);
  }
  instance.off('click');
});
defineExpose({
  ...props,
  search,
  setOption,
  widget: props.widget,
});
</script>

<style lang="scss" scoped>
@include c('bi-pie-block') {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  @include e('header') {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: var(--md-spacing-2);
  }
  @include e('label') {
    color: #222;
    font-size: var(--md-font-3);
  }
  @include e('body') {
    flex: 1;
  }
}
</style>
